﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine;
using Engine.Graphics;
using Engine.Physics;
using Microsoft.Xna.Framework;

namespace Playtime
{
    public enum GamePlayState
    {
        Running,
        Paused,
        Lost
    }
    public class World : Component
    {
        LevelData data;

        public static World Instance { get; private set; }

        public List<Platform> Platforms {get { return data.Platforms; }}
        public Player Player;
        public GamePlayState State { get; private set; }

        public World()
        {
            Instance = this;
            State = GamePlayState.Running;
            Player = GameObject.Initialize("Player", GraphicsEngine.Instance.Resolution / 2, gameObject,
                                  new Dictionary<Type, object[]>
                                  {
                                      {typeof(JointStructure), new object[]{"test3.char"}},
                                      {typeof(JointAnimationContainer), new object[]{new List<string>(){"test3.char"}}},
                                      {typeof(Player), new object[]{}},
                                      {typeof(Collider), new object[]{new Rectangle(0,0,100, 200), true}}
                                  }).GetComponent<Player>();


            GameObject.Initialize("Camera", Vector2.Zero, new Dictionary<Type, object[]>()
            {
                {typeof(Camera), new object[]{Color.White}}
            });

        }

        public World(LevelData _data) : this()
        {
            data = _data;
            foreach (Platform platform in Platforms)
            {
                Vector2 diff = platform.end - platform.start;
                
                float length = diff.Length();
                diff.Normalize();

                if (float.IsNaN(diff.X) || float.IsNaN(diff.Y))
                    continue;
                float rotation = (float)Math.Acos(Vector2.Dot(diff, Vector2.UnitX)) * Math.Sign(diff.Y);
                if (rotation > MathHelper.PiOver2)
                    rotation -= MathHelper.Pi;
                else if (rotation < -MathHelper.PiOver2)
                    rotation += MathHelper.Pi;

                GameObject newPlat = GameObject.Initialize("Platform", (platform.start + platform.end) / 2, gameObject, new Dictionary<Type, object[]>()
                {
                    {typeof(Collider), new object[]{ new Rectangle((int)(-length/2), -15, (int)length, 30), true}}
                });
                newPlat.transform.Rotation = rotation;
            }
        }

        public override void Update(GameTime _gameTime)
        {
            /*if (Player.gameObject.collider.AABB.Bottom > GraphicsEngine.Instance.Resolution.Y)
                State = GamePlayState.Lost;*/
        }
    }
}
